package com.sky.aspect;

import com.sky.annotation.AutoFill;
import com.sky.constant.AutoFillConstant;
import com.sky.context.BaseContext;
import com.sky.enumeration.OperationType;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.time.LocalDateTime;

/**
 *自定义切面,实现公共字段自动填充逻辑
 */

@Aspect
@Slf4j
@Component
public class AutoFillAspect {
    /**
     *切入点
     */
    @Pointcut("execution(* com.sky.mapper.*.*(..)) && @annotation(com.sky.annotation.AutoFill)")
    public void autoFillPointCut() {}

    /**
     *前置通知,填充公共字段
     */
    @Before("autoFillPointCut()")
    public void autoFill(JoinPoint joinPoint) {
       MethodSignature methodSignature= (MethodSignature)joinPoint.getSignature();
       AutoFill autoFill = methodSignature.getMethod().getAnnotation(AutoFill.class);
         Object[] args = joinPoint.getArgs();
       if (args.length==0 || args==null)
       {
           return;
       }

        LocalDateTime now = LocalDateTime.now();
        Long currentId = BaseContext.getCurrentId();
        Object entity= args[0];
        try {
            if (autoFill.value()== OperationType.INSERT)
            {
                Method method1 = entity.getClass().getDeclaredMethod(AutoFillConstant.SET_CREATE_TIME,LocalDateTime.class);
                Method method2 = entity.getClass().getDeclaredMethod(AutoFillConstant.SET_CREATE_USER,Long.class);
                Method method3 = entity.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_TIME,LocalDateTime.class);
                Method method4 = entity.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_USER,Long.class);

                method1.invoke(entity,now);
                method2.invoke(entity,currentId);
                method3.invoke(entity,now);
                method4.invoke(entity,currentId);

            }else
            {
                Method method3 = entity.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_TIME,LocalDateTime.class);
                Method method4 = entity.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_USER,Long.class);
                method3.invoke(entity,now);
                method4.invoke(entity,currentId);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}
